/*
    Copyright is LuoYuShun to 2022-2022
*/
package cn.com.laya.service.fourdemo.deals;

import cn.com.laya.service.fourdemo.bean.ResultResponse;
import cn.com.laya.service.fourdemo.bean.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * web socket消息的工程类
 *
 * @author LuoYuShun
 * @since 2022-11-24
 */
@Component
@Slf4j
public class WebSocketMessageFactory {
    /**
     * 消息处理器
     */
    @Resource
    private List<MessageDealHandler> messageHandlers;

    /**
     * web的socket处理消息的类型
     */
    public static final String WEB_SOCKET_HANDLER_TYPE = "webSocketHandler";

    /**
     * 处理的消息信息
     *
     * @param webSocketMessage web的消息
     * @param fallbackInvoke 回调数据
     */
    public void dealMessage(WebSocketMessage webSocketMessage, Consumer<ResultResponse<?>> fallbackInvoke) {
        MessageDealHandler messageDealHandler = messageHandlers.stream()
                .filter(item -> item.isHandler(webSocketMessage.getMessageType(), WEB_SOCKET_HANDLER_TYPE))
                .findFirst().orElse(null);
        if (Objects.nonNull(messageDealHandler)) {
            // 进行消息的处理
            messageDealHandler.dealMessage(webSocketMessage, fallbackInvoke);
        }
        log.error("处理器为空，处理失败!");
        ResultResponse<?> resultResponse = new ResultResponse<>();
        resultResponse.setCode("300");
        resultResponse.setMsg("没有获取到对应的处理器");
        if (Objects.nonNull(fallbackInvoke)) {
            fallbackInvoke.accept(resultResponse);
        }
    }
}
